package com.battery.web.controller.system.battery;

import java.math.BigDecimal;
import java.util.List;

import com.battery.common.utils.BatteryJSONResult;
import com.battery.common.utils.ali.AliPayEntity;
import com.battery.framework.config.properties.AliPayResource;
import com.battery.system.domain.BO.UsedBO;
import com.battery.system.domain.VO.UsedDetailVo;
import com.battery.system.domain.VO.UsedVO;
import com.battery.system.service.battery.IAuthUsedService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.battery.common.annotation.Log;
import com.battery.common.enums.BusinessType;
import com.battery.system.domain.Used;
import com.battery.system.service.battery.IUsedService;
import com.battery.common.core.controller.BaseController;
import com.battery.common.core.domain.AjaxResult;
import com.battery.common.utils.poi.ExcelUtil;
import com.battery.common.core.page.TableDataInfo;

/**
 * 租借订单Controller
 *
 * @author battery
 * @date 2021-01-26
 */
@Controller
@RequestMapping("/system/used")
public class UsedController extends BaseController {
    private String prefix = "system/used";

    @Autowired
    private IUsedService usedService;

    @Autowired
    private IAuthUsedService authUsedService;

    @Autowired
    private AliPayResource aliPayResource;


    private AliPayEntity _callApi() {
        AliPayEntity entity = new AliPayEntity();
        entity.setAppId(aliPayResource.getAppId());
        entity.setAlipayPublicKey(aliPayResource.getAlipayPublicKey());
        entity.setCharset(aliPayResource.getCharset());
        entity.setGatewayUrl(aliPayResource.getGatewayUrl());
        entity.setMerchantPrivateKey(aliPayResource.getMerchantPrivateKey());
        entity.setSignType(aliPayResource.getSignType());
        entity.setNotifyUrl(aliPayResource.getNotifyUrl());
        entity.setPayeeLogonId(aliPayResource.getPayeeLogonId());
        entity.setPayeeUserId(aliPayResource.getPayeeUserId());
        entity.setFreezeNotifyUrl(aliPayResource.getFreezeNotifyUrl());
        entity.setServiceId(aliPayResource.getServiceId());
        return entity;
    }


    @RequiresPermissions("system:used:isBackUsed:view")
    @GetMapping("isBackUsed")
    public String isBackUsed(ModelMap mmap) {
        mmap.put("isBack", 1);
        return prefix + "/backUsed";
    }


    @RequiresPermissions("system:used:onUsed:view")
    @GetMapping("/onUsed")
    public String onUsed(ModelMap mmap) {
        mmap.put("isBack", 0);
        return prefix + "/onUsed";
    }


    /**
     * 租借记录
     *
     * @return
     */
    @RequiresPermissions("system:used:m:view")
    @GetMapping("/m_used")
    public String m_used() {
        return prefix + "/m_used";
    }

    /**
     * 查询租借订单列表
     */
    @RequiresPermissions("system:used:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(UsedBO usedBO) {
        startPage();
//        List<Used> list = usedService.selectUsedList(used);
        List<UsedVO> list = usedService.selectUsedVOList(usedBO);
        return getDataTable(list);
    }

    /**
     * 导出租借订单列表
     */
    @RequiresPermissions("system:used:export")
    @Log(title = "租借订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Used used) {
        List<Used> list = usedService.selectUsedList(used);
        ExcelUtil<Used> util = new ExcelUtil<Used>(Used.class);
        return util.exportExcel(list, "used");
    }

    /**
     * 新增租借订单
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存租借订单
     */
    @RequiresPermissions("system:used:add")
    @Log(title = "租借订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Used used) {
        return toAjax(usedService.insertUsed(used));
    }

    /**
     * 修改租借订单
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        Used used = usedService.selectUsedById(id);
        mmap.put("used", used);
        return prefix + "/edit";
    }


    /**
     * 展示租借详情记录
     *
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/seeDetails/{id}")
    public String seeDetails(@PathVariable("id") String id, ModelMap mmap) {
        UsedDetailVo usedDetailVo = usedService.selectUsedDetails(id);
        mmap.put("usedDetailVo", usedDetailVo);
        return prefix + "/showDetail";
    }


    /**
     * 跳转到退款页面
     *
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/refundMoney/{id}")
    public String refundMoney(@PathVariable("id") String id, ModelMap mmap) {
        Used used = usedService.selectByPrimaryKey(id);
        mmap.put("id", used.getTrueOrderId());
        return prefix + "/refundMoney";
    }


    /**
     * 修改保存租借订单
     */
    @RequiresPermissions("system:used:edit")
    @Log(title = "租借订单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Used used) {
        return toAjax(usedService.updateUsed(used));
    }

    /**
     * 删除租借订单
     */
    @RequiresPermissions("system:used:remove")
    @Log(title = "租借订单", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(usedService.deleteUsedByIds(ids));
    }


    /**
     * 跳转到结束订单界面
     *
     * @param id
     * @return
     */
    @GetMapping("/endUsed/{id}")
    public String endUsed(@PathVariable("id") String id, ModelMap mmap) {
        mmap.put("id", id);
        return prefix + "/endUsed";
    }


    /**
     * 结束订单
     *
     * @param used
     * @return
     */
    @RequiresPermissions("system:used:endUsed")
    @Log(title = "结束订单", businessType = BusinessType.UPDATE)
    @PostMapping("/endUsed")
    @ResponseBody
    public AjaxResult endUsed(Used used) {

        if (StringUtils.isBlank(used.getId())) {
            return error("主键ID为空");
        }

        if (used.getAmountPaid() == null) {
            return error("请填写扣费金额");
        }

        if (used.getAmountPaid().compareTo(BigDecimal.ZERO) < 0) {
            return error("填写的金额不能小于0");
        }

        AliPayEntity entity = _callApi();
        return usedService.backstageEndUsed(used, entity);
    }

    // TODO 免押租借订单列表 ========================== start


    /**
     * 跳转到微信免押订单页面
     *
     * @return
     */
    @RequiresPermissions("system:used:auth:wx:view")
    @GetMapping("/wx.auth")
    public String wxAuth() {
        return prefix + "/wx_auth";
    }


    /**
     * 微信免押订单列表
     *
     * @param usedBO
     * @return
     */
    @RequiresPermissions("system:used:auth:wx:list")
    @PostMapping("/wx.auth.list")
    @ResponseBody
    public TableDataInfo wxAuthList(UsedBO usedBO) {
        startPage();
        List<UsedVO> list = authUsedService.wxAuthList(usedBO);
        return getDataTable(list);
    }


    @Log(title = "微信支付分取消订单", businessType = BusinessType.OTHER)
    @RequiresPermissions("system:used:auth:cancel")
    @PostMapping("/wxCancel")
    @ResponseBody
    public AjaxResult wxCancel(String id) {
        if (StringUtils.isBlank(id)) {
            return error("ID为空");
        }
        // 撤销订单
        BatteryJSONResult result = authUsedService.doWxRevokeOrder(id);
        if (result == null) {
            return error("微信支付分取消订单失败！");
        }
        if (result.getCode() == 1) {
            return success("撤销成功");
        }
        return error(result.getMsg());
    }

    @Log(title = "微信支付分发起扣款", businessType = BusinessType.OTHER)
    @RequiresPermissions("system:used:auth:requestPay")
    @PostMapping("/requestWxFreePay")
    @ResponseBody
    public AjaxResult requestWxFreePay(String id) {
        if (StringUtils.isBlank(id)) {
            return error("ID为空");
        }
        return authUsedService.requestWxFreePay(id);
    }


    /**
     * 跳转到微信免押订单页面
     *
     * @return
     */
    @RequiresPermissions("system:used:auth:ali:view")
    @GetMapping("/ali.auth")
    public String aliAuth() {
        return prefix + "/ali_auth";
    }


    /**
     * 支付宝免押订单列表
     *
     * @param usedBO
     * @return
     */
    @RequiresPermissions("system:used:auth:ali:list")
    @PostMapping("/ali.auth.list")
    @ResponseBody
    public TableDataInfo aliAuthList(UsedBO usedBO) {
        startPage();
        List<UsedVO> list = authUsedService.aliAuthList(usedBO);
        return getDataTable(list);
    }


    @Log(title = "支付宝预授权解冻订单", businessType = BusinessType.OTHER)
    @RequiresPermissions("system:used:auth:cancel")
    @PostMapping("/aliCancel")
    @ResponseBody
    public AjaxResult aliCancel(String id) {
        if (StringUtils.isBlank(id)) {
            return error("ID为空");
        }
        AliPayEntity entity = _callApi();
        BatteryJSONResult result = authUsedService.doUnfreeze(id, entity);
        if (result == null) {
            return error("支付宝预授权解冻订单失败！");
        }
        if (result.getCode() == 1) {
            return success("撤销成功");
        }
        return error(result.getMsg());
    }


    @Log(title = "支付宝预授权发起扣款", businessType = BusinessType.OTHER)
    @RequiresPermissions("system:used:auth:requestPay")
    @PostMapping("/requestAliFreePay")
    @ResponseBody
    public AjaxResult requestAliFreePay(String id) {
        // https://opensupport.alipay.com/support/helpcenter/128/201602490591?ant_source=zsearch
        if (StringUtils.isBlank(id)) {
            return error("ID为空");
        }
        AliPayEntity entity = _callApi();
        return authUsedService.requestAliFreePay(id, entity);
    }


    // TODO 免押租借订单列表 ========================== end


}
